#include "app_pwm.h"
#include "app_common.h"
#include "tkl_pwm.h"
#include "tal_pwm.h"
#include "tal_log.h"

#define PWM_MIN_FREQ            100   ///< PWM MIN Frequency 100
#define PWM_MAX_FREQ            20000 ///< PWM MAX Frequency 20K
#define PWM_MAX_DUTY            1000  ///< PWM MAX Duty 1000 --> Precision 0.1%

#define PWM_FREQUENCY           3800

#define COLD_CHANNE TUYA_PWM_NUM_0
#define WARM_CHANNE TUYA_PWM_NUM_1

BOOL_T g_user_pwm_init_flag = FALSE;

extern OPERATE_RET tkl_pwm_mapping_to_gpio(UINT32_T ch_id, UINT32_T gpio_id);
extern OPERATE_RET tkl_pwm_idle_level_set(TUYA_PWM_NUM_E ch_id, UINT8_T idle_level);

OPERATE_RET app_pwm_cw_set(USHORT_T c_value, USHORT_T w_value)
{
    if (g_user_pwm_init_flag != TRUE)
    {
        TAL_PR_DEBUG("user pwm not init!");
        return OPRT_INVALID_PARM;
    }
    if ((c_value > PWM_MAX_DUTY) || (w_value > PWM_MAX_DUTY))
    {
        TAL_PR_DEBUG("USER PWM data is invalid!");
        return OPRT_INVALID_PARM;
    }

    c_value = (int)c_value * PWM_FREQUENCY / PWM_MAX_DUTY;
    w_value = (int)w_value * PWM_FREQUENCY / PWM_MAX_DUTY;
    tal_pwm_duty_set(COLD_CHANNE, c_value); /* send C value */
    tal_pwm_duty_set(WARM_CHANNE, w_value); /* send W value */
    tal_pwm_start(0xFF);
        
    return OPRT_OK;
}

/**
 * @brief 
 * 
 * @return OPERATE_RET 
 */
OPERATE_RET app_pwm_init(VOID_T)
{
    OPERATE_RET v_ret = OPRT_COM_ERROR;

    tkl_pwm_mapping_to_gpio((UINT32_T)TUYA_PWM_NUM_0, USER_PWM_CH0_PIN); //PB4
    tkl_pwm_mapping_to_gpio((UINT32_T)TUYA_PWM_NUM_1, USER_PWM_CH1_PIN); //PB5
    
    TUYA_PWM_BASE_CFG_T v_cfg = {
        .duty = 0,
        .cycle = PWM_FREQUENCY,
        .frequency = PWM_FREQUENCY,
        .polarity = TUYA_PWM_POSITIVE,
    };

    tkl_pwm_idle_level_set(TUYA_PWM_NUM_0, 0);
    tkl_pwm_idle_level_set(TUYA_PWM_NUM_1, 0);
    
    v_ret = tal_pwm_init(TUYA_PWM_NUM_0, &v_cfg);
    v_ret = tal_pwm_init(TUYA_PWM_NUM_1, &v_cfg);

    tal_pwm_start(0xFF);

    g_user_pwm_init_flag = TRUE;
    TAL_PR_DEBUG("pwm init ok!");
    return v_ret;
}

